const devWebpack = require('./build/webpack.dev.config');
const proWebpack = require('./build/webpack.prod.config');
const anaWebpack = require('./build/webpack.analyze.config');
const webpack = require('webpack');
const chalk = require('chalk');
const config = require('./config');
const log = console.log;
// const rimraf = require('rimraf');
// webpack --env.NODE_ENV=local --env.production --progress

module.exports = env => {
  log(chalk.bgGreen.black('START RUN ENV ', (env ? env : 'null').toUpperCase()));

  let webpackConfig = null;
  let NODE_ENV = null;

  switch (env) {
    case 'production':
      webpackConfig = proWebpack;
      NODE_ENV = 'PRO';
      break;
    case 'analyze':
      webpackConfig = anaWebpack;
      NODE_ENV = 'DEV';
      break;
    default:
      webpackConfig = devWebpack;
      NODE_ENV = env === 'test' ? 'TEST' : 'DEV';
      break;
  }

  try {
    if (JSON.parse(process.env.npm_config_argv)['original'][2]) {
      const argvParam = JSON.parse(process.env.npm_config_argv)['original'][2].toUpperCase();
      NODE_ENV = argvParam.replace('--', '');
    }
    log(chalk.blue('SET:', JSON.stringify(config[NODE_ENV])));
    log(chalk.black.bgGreen('HELLO WELCOME TO '+ NODE_ENV +' ENVIRONMENTAL, WISH YOU WELL! \n'));
    webpackConfig.plugins.push(new webpack.EnvironmentPlugin(config[NODE_ENV]))
  } catch (err) {
    log(chalk.red('webpack.config.js report err:', err));
  }

  return webpackConfig;
};
